package com.itelite.common.util;

import com.itelite.domain.pojo.LoginUser;
import com.itelite.domain.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 **/
@Slf4j
public class SecurityUtils {

    private final static String[] agent = { "Android", "iPhone", "iPod","iPad", "Windows Phone", "MQQBrowser" }; //定义移动端请求的所有可能类型

    /**
     * 判断User-Agent 是不是来自于手机
     */
    public static boolean checkAgentIsMobile(String ua) {
        boolean flag = false;
        if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
            // 排除 苹果桌面系统
            if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
                for (String item : agent) {
                    if (ua.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    public static String getUsername(){
        return getUser().getUsername();
    }
    public static LoginUser getUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            return null;
        }else return (LoginUser) authentication.getPrincipal();
    }
    public static Integer getGroupId(){
        return getUser().getGroupId();
    }
    public static Integer getUserId(){
        return getUser().getUserId();
    }
    public static String getRealName(){
        LoginUser user = getUser();
        if(user==null){
            return "未登录用户";
        }else return user.getRealName();
    }
}
